import { wxAppconstant } from './wxconstant';

let token = sessionStorage.getItem("TcslSlyunToken") ? sessionStorage.getItem("TcslSlyunToken") : '';

export const ajaxGet = (url, pathKey) => {
    return fetchData({ url: url, pathKey: pathKey || false, method: 'GET' }).then(json => {
        return Promise.resolve(json);
    }).catch(err => {
        return Promise.reject(err);
    })
}

export const ajaxDelect = (url, pathKey) => {
    return fetchData({ url: url, pathKey: pathKey || false, method: 'DELETE' }).then(json => {
        return Promise.resolve(json);
    }).catch(err => {
        return Promise.reject(err);
    })
}

export const ajaxPost = (url, data, pathKey) => {
    return fetchData({ url: url, pathKey: pathKey || false, data: data, method: 'POST' }).then(json => {
        return Promise.resolve(json);
    }).catch(err => {
        return Promise.reject(err);
    })
}

export const ajaxPut = (url, data, pathKey) => {
    return fetchData({ url: url, pathKey: pathKey || false, data: data, method: 'PUT' }).then(json => {
        return Promise.resolve(json);
    }).catch(err => {
        return Promise.reject(err);
    })
}
function fetchData(options) {
    var key = options.pathKey || 'slyApiPath';
    var fetchObj = {
        method: options['method'] ? options['method'].toUpperCase() : 'GET',
        mode: options['cors'] || 'cors',
        headers: options['headers'] || { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: options['data'] || {}
    };
    fetchObj['body'] = JSON.stringify(fetchObj['body']);
    console.log(JSON.stringify(fetchObj['body']));
    if (fetchObj['method'] == "GET" || fetchObj['method'] == "HEAD") {
        delete fetchObj['body'];
    }
    fetchObj['headers']['Tcsl-Slyun-Token'] = token;
    return fetch(wxAppconstant[wxAppconstant['profile']][key] + options['url'], fetchObj).then(res => res.json()).catch(err => {
        return Promise.reject(err);
    });

}